# -*- coding: utf-8 -*
import re
import subprocess

from ..common import Collector


class UsageCollector(Collector):
    """CPU使用率收集器：收集 %usr，%sys，%iowait，%irq，%soft，%nice，%idle 七个浮点数"""
    def __init__(self, is_test):
        super().__init__(is_test)
        self.metric_dict = {
            "usr": 0.0,
            "sys": 0.0,
            "iowait": 0.0,
            "irq": 0.0,
            "soft": 0.0,
            "nice": 0.0,
            "idle": 0.0
        }

    def get_metric(self, metric: str) -> float:
        """获取cpu使用率中的某项具体指标"""
        return self.metric_dict[metric]

    def collect(self) -> None:
        if self.is_test:
            test_file_path = Collector.get_test_file_path("mpstat.txt", __file__)
            with open(test_file_path, "r", encoding="utf-8") as f:
                lines = f.readlines()
                head_line = lines[0]
                tail_line = lines[-1]

            # 正则匹配所有空白符，替换成单个空格，方便处理
            pat = re.compile(r"\s+")
            head_line = pat.sub(" ", head_line)
            head_line_list = head_line.split(" ")
            tail_line = pat.sub(" ", tail_line)
            tail_line_list = tail_line.split(" ")

            # 要整体情况
            cpu = tail_line_list[1]
            if cpu == "all":
                for metric in self.metric_dict.keys():
                    idx = head_line_list.index("%" + metric)
                    self.metric_dict[metric] = float(tail_line_list[idx])
                    self.stash.append(float(tail_line_list[idx]))
        else:
            process_out = subprocess.run(["mpstat", "1", "1"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            out_str = str(process_out.stdout, encoding="utf-8")

            heading_pat = re.compile(r"%[a-z]{3,}")  # 识别指标表头
            metric_pat = re.compile(r"\d{1,2}\.\d{2}")  # 识别指标具体值

            heading_list = heading_pat.findall(out_str)
            metric_list = metric_pat.findall(out_str)[-10:]
            for metric in self.metric_dict.keys():
                idx = heading_list.index("%" + metric)
                self.metric_dict[metric] = float(metric_list[idx])
                self.stash.append(float(metric_list[idx]))
